<!DOCTYPE html>
<html lang="zh-ch">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖动</title>
    <style>
      body {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .list {
        margin-top: 50px;
      }
      .list-item {
        height: 40px;
        width: 700px;
        background-color: #40b0be;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 20px;
        border-radius: 5px;
        color: white;
      }
      .list .moving {
        background: transparent;
        color: transparent;
        border: 1px dashed #ccc;
      }
      .balck {
        background-color: black;
      }
    </style>
  </head>
  <body>
    <div class="list">
    </div>

    <script>
      let array = [1, 2, 3, 4, 5, 6, 7];
      const list = document.querySelector(".list");
      let sourceNode;
      function load() {
        array.forEach((element) => {
          //使用js创建calss为ist-item的div
          let itemDiv = document.createElement("div");
          itemDiv.setAttribute("draggable", "true");
          itemDiv.classList.add("list-item");
          itemDiv.innerHTML = element;
          list.appendChild(itemDiv);
        });
      }
      load();

      list.ondragstart = (e) => {
        // console.log(e);
        setTimeout(() => {
          e.target.classList.add("moving");
        }, 0);
        sourceNode = e.target;
        e.dataTransfer.effectAllowed = "move";
      };

      list.ondragenter = (e) => {
        e.preventDefault(); // 取消默认行为
        if (e.target == list || e.target == sourceNode) return;

        const children = Array.from(list.children);
        const sourceIndex = children.indexOf(sourceNode);
        const targetIndex = children.indexOf(e.target);

        console.log(sourceIndex);
        console.log(targetIndex);



        if (sourceIndex < targetIndex) {
          console.log("向下拖动");
          list.insertBefore(sourceNode, e.target.nextElementSibling);
        } else {
          console.log("向上拖动");
          list.insertBefore(sourceNode, e.target);
        }
      };

      list.ondragend = (e) => {
        e.target.classList.remove("moving");
      };

      list.ondragover = (e) => {
        e.preventDefault();
      };
    </script>
  </body>
</html>
